using System;
using MVP.DTO;
using MVP.Task;

namespace MVP.Presentation
{
    public class ViewCustomerPresenter
    {
        private readonly IViewCustomerView view;
        private readonly ICustomerTask task;

        public ViewCustomerPresenter(IViewCustomerView view) : this(view, new CustomerTask()) {}

        public ViewCustomerPresenter(IViewCustomerView view, ICustomerTask task)
        {
            this.view = view;
            this.task = task;
        }

        public void Initialize()
        {
            task.GetCustomerList().BindTo(view.CustomerList);
        }

        public void DisplayCustomerDetails()
        {
            int? customerId = SelectedCustomerId;

            if (customerId.HasValue)
            {
                CustomerDTO customer = task.GetDetailsForCustomer(customerId.Value);
                UpdateViewFrom(customer);
            }
        }

        private int? SelectedCustomerId
        {
            get
            {
				string selectedId = view.CustomerList.SelectedItem.Value;
				
                if (String.IsNullOrEmpty(selectedId)) return null;

                int? id = null;

                try
                {
                    id = int.Parse(selectedId.Trim());
                }
                catch (FormatException) {}

                return id;
            }
        }

        private void UpdateViewFrom(CustomerDTO customer)
        {
            view.CompanyName = customer.CompanyName;
            view.ContactName = customer.ContactName;
            view.ContactTitle = customer.ContactTitle;
            view.Address = customer.Address;
            view.City = customer.City;
            view.Region = customer.Region;
            view.Country = customer.CountryOfResidence.Name;
            view.Phone = customer.Phone;
            view.Fax = customer.Fax;
            view.PostalCode = customer.PostalCode;
        }
    }
}